﻿#include "copyoperator.h"
#include<QDir>
#include<QDirIterator>
#include<QFileInfo>
#include<QDebug>
#include<QFile>
CopyOperator::CopyOperator(const char *source, const char *direct):
                        sourcePath(source),directPath(direct),FileCallBack(nullptr)
{
signalTemp = new SignalTemp;
}

CopyOperator::~CopyOperator()
{

}

void CopyOperator::SetFileInfoCallBack(const std::function<void (const QString,const QString)> &fun)
{
    FileCallBack = fun;
}

void CopyOperator::GetFileFolderChildren(QString path)
{
    if(sourcePath == nullptr)
    {
        qDebug()<<"sourcePath is NULL";
        return;
    }

    QDir directory(path);
    directory.setFilter(QDir::Dirs);
    foreach(QFileInfo fullDir,directory.entryInfoList())
    {
        if(fullDir.fileName()=="." || fullDir.fileName()=="..")
        {
            continue;
        }
        QString dirPath;
        dirPath.append(fullDir.dir().path());
        dirPath.append("/");
        dirPath.append(fullDir.fileName());
//        qDebug()<<dirPath;
        GetFileFolderChildren(dirPath);
        GetFolderFiles(dirPath);
        qDebug()<<fullDir.fileName();
    }
    emit signalTemp->sendFileStatus("path","该所有文件复制完成");
}

void CopyOperator::GetFolderFiles(QString dirPath)
{
    qDebug()<<"DIR:"<<dirPath;
    if(dirPath == nullptr)
    {
        return;
    }
    QDir dir(dirPath);
    QStringList filters;

    QDirIterator iter(dir,QDirIterator::Subdirectories);
    while(iter.hasNext())
    {
        iter.next();
        QFileInfo info = iter.fileInfo();
        if(info.isFile())
        {
            qDebug()<<info.absoluteFilePath();
            qDebug()<<info.fileName();
           emit signalTemp->sendFileStatus(info.absoluteFilePath(),"开始复制");

            bool ok = QFile::copy(info.absoluteFilePath(),directPath+"/"+info.fileName());

            if(ok)
            {emit signalTemp->sendFileStatus(info.absoluteFilePath(),"===复制完成===");
            }
            else {
                emit signalTemp->sendFileStatus(info.absoluteFilePath(),"复制失败");
            }
//            qDebug()<<info.bundleName();
        }
    }

}

void CopyOperator::run()
{
    GetFileFolderChildren(sourcePath);
    emit signalTemp->sendFileStatus("ALL","已完成所有文件复制");
}
